﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data;
using System.IO;
using System.Text;
using System.Configuration;

namespace WebAddressBook
{
    public partial class ManageCompany : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitDataGridView();
            }

        }

        protected void BtCreate_Click(object sender, EventArgs e)
        {
            if (!VerifyIuput())
            {
                LbMessage.Text = "<div class='box box-error'>带有 * 字段不能为空值！</div>";
                return;
            }

            try
            {
                Guid guid = new Guid(secretKey.Value.Trim());
            }
            catch
            {
                LbMessage.Text = "<div class='box box-error'>是非法密钥！</div>";
                return;
            }
            //根据密钥去主服务器拿DeptID回来
            string deptID = VerifySecretKey(secretKey.Value.Trim());
            if (string.IsNullOrEmpty(deptID))
            {
                return;
            }
            else
            {
                Adrr.BLL.Base_Dept baseDeptBll = new Adrr.BLL.Base_Dept();
                Adrr.Model.Base_Dept baseDeptModel = new Adrr.Model.Base_Dept();

                //DataSet ds= baseDeptBll.GetAllList();
                baseDeptModel.DeptID = deptID;
                baseDeptModel.DeptName = enterpriseName.Value.Trim();
                baseDeptModel.DeptBriefName = enterpriseShortName.Value.Trim();
                baseDeptModel.IsWorkDress = Convert.ToBoolean(isWorkAddress.SelectedValue);
                //TODO:
                //需求是：如果是办公地点才可以设置电话，暂时都可以设置，待做控制
                baseDeptModel.PhoneNum = phoneNum.Value.Trim();
                baseDeptModel.CreateTime = DateTime.Now;
                baseDeptModel.UpdateTime = DateTime.Now;
                baseDeptModel.isDelete = false;
                baseDeptModel.PinYin = enterprisePinYin.Value.Trim();

                if (baseDeptBll.Add(baseDeptModel))
                {
                    LbMessage.Text = "<div class='box box-info'>添加成功！</div>";
                    InitDataGridView();
                    ClearUI();
                }
                else
                    LbMessage.Text = "<div class='box box-error'>添加失败！</div>";
            }
        }
        /// <summary>
        /// 根据密钥进行验证
        /// </summary>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        private string VerifySecretKey(string secretKey)
        {
            StringBuilder url = new StringBuilder();
            url.Append(ConfigurationManager.AppSettings["VerifyAddress"].ToString());
            url.Append("/GetEnterpriseCode.aspx?SecretKey=");
            url.Append(secretKey);
            try
            {
                WebRequest request = WebRequest.Create(url.ToString());
                WebResponse response = request.GetResponse();
                Stream s = response.GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.GetEncoding("gb2312"));
                string code = sr.ReadToEnd();
                switch (code.ToUpper())
                {
                    case "NOTEXIST":
                        LbMessage.Text = "<div class='box box-error'>密钥不存在！</div>";
                        return null;
                    case "BEUSED":
                        LbMessage.Text = "<div class='box box-error'>密钥已经被占用！</div>";
                        return null;
                    default: return code;
                }
            }
            catch (Exception ex)
            {
                LbMessage.Text = "<div class='box box-error'>"+ex.Message+"</div>";
                return null;
            }
        }
        /// <summary>
        /// 初始化数据表
        /// </summary>
        private void InitDataGridView()
        {
            DataSet ds = CommonHelper.GetEnterprise();
            GridView1.DataSource = ds;
            GridView1.DataKeyNames = new string[] { "DeptID" };
            GridView1.DataBind();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string deptId = GridView1.DataKeys[e.RowIndex].Value.ToString();
            Adrr.BLL.Base_Dept baseDeptBll = new Adrr.BLL.Base_Dept();
            baseDeptBll.SetThisCompanyIsDepted(deptId);
            SetAllThisCompanyEmployeeBeDeleted(deptId);
            //刷新数据
            InitDataGridView();
        }
        /// <summary>
        ///删除该企业下的所有员工
        /// </summary>
        /// <param name="deptId">企业ID</param>
        private void SetAllThisCompanyEmployeeBeDeleted(string deptId)
        {
            Adrr.BLL.Base_Employee base_EmployeeBll = new Adrr.BLL.Base_Employee();
            base_EmployeeBll.SetAllThisCompanyEmployeeBeDeleted(deptId);
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //如果是绑定数据行 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    ((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('删除操作将删除该企业下的部门和员工，你确认要删除该企业吗?')");
                }
            }
        }
        /// <summary>
        /// 清空ui上输入的值
        /// </summary>
        private void ClearUI()
        {
            secretKey.Value = "";
            enterpriseName.Value = "";
            enterpriseShortName.Value = "";
            enterprisePinYin.Value = "";
            phoneNum.Value = "";
        }
        /// <summary>
        /// 验证输入的不能为空
        /// </summary>
        /// <returns></returns>
        private bool VerifyIuput()
        {
            if (string.IsNullOrEmpty(secretKey.Value.Trim()) || string.IsNullOrEmpty(enterpriseName.Value.Trim())
                || string.IsNullOrEmpty(enterpriseShortName.Value.Trim()) || string.IsNullOrEmpty(enterprisePinYin.Value.Trim())
                || string.IsNullOrEmpty(phoneNum.Value.Trim()))
                return false;
            else
                return true;
        }

    }
}